package stark.app.function.pdf;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.stark.doc.selector.DefDocSelActivity;
import com.stark.pdf.lib.model.IPdf2ImgListener;
import com.stark.pdf.lib.model.IPdfCreateListener;
import com.stark.pdf.lib.model.PdfUtil;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import stark.app.R;
import stark.app.databinding.ActivityPdfDemoBinding;
import stark.app.function.tbs.TbsReaderActivity;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.inf.IRetCallback;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.utils.IntentUtil;

/**
 * Author：daizhongbin on 2021/12/14
 * Email：1027154338@qq.com
 * Desc:
 */
public class PdfDemoActivity extends BaseNoModelActivity<ActivityPdfDemoBinding> {

    private static final int FUNC_SAVE_2_PDF = 1;
    private static final int FUNC_IMG_2_PDF = 2;
    private static final int FUNC_PDF_2_IMG = 3;

    private static final int REQ_PDF_2_IMG = 1;

    @Override
    protected int onCreate() {
        return R.layout.activity_pdf_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnSave2Pdf.setOnClickListener(v -> {
            reqPermission(FUNC_SAVE_2_PDF);
        });
        mDataBinding.btnImg2Pdf.setOnClickListener(v -> {
            reqPermission(FUNC_IMG_2_PDF);
        });
        mDataBinding.btnPdf2Img.setOnClickListener(v -> {
            reqPermission(FUNC_PDF_2_IMG);
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) return;

        if (requestCode == REQ_PDF_2_IMG) {
            MediaInfo mediaInfo = (MediaInfo) data.getSerializableExtra(Extra.DATA);
            pdf2Img(Uri.parse(mediaInfo.getUri()));
        }
    }

    private void reqPermission(int func) {
        PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .callback(new PermissionUtils.SingleCallback() {
                    @Override
                    public void callback(boolean isAllGranted, @NonNull List<String> granted, @NonNull List<String> deniedForever, @NonNull List<String> denied) {
                        if (!isAllGranted) {
                            ToastUtils.showShort("请先授予权限");
                            return;
                        }

                        switch (func) {
                            case FUNC_SAVE_2_PDF:
                                createPdf();
                                break;
                            case FUNC_IMG_2_PDF:
                                img2Pdf();
                                break;
                            case FUNC_PDF_2_IMG:
                                pdf2Img();
                                break;
                        }
                    }
                })
                .request();

    }

    private void createPdf() {
        showDialog("处理中...");
        String content = "爱是什么？\n" +
                "一个精灵坐在碧绿的枝叶间沉思。\n" +
                "风儿若有若无。\n" +
                "一只鸟儿飞过来，停在枝上，望着远处将要成熟的稻田。\n" +
                "精灵取出一束黄澄澄的稻谷问道：“你爱这稻谷吗？”";
        PdfUtil.createPdf(content, new IRetCallback<String>() {
            @Override
            public void onResult(String result) {
                IntentUtil.shareFile(PdfDemoActivity.this, result);
                dismissDialog();
            }
        });
    }

    private void img2Pdf() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .maxCount(10)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        if (data == null || data.size() == 0) {
                            return;
                        }

                        List<String> imgPathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            imgPathList.add(entity.getPath());
                        }
                        PdfUtil.img2Pdf(imgPathList, new IPdfCreateListener() {
                            @Override
                            public void onStart() {
                                showDialog("转换中...");
                            }

                            @Override
                            public void onEnd(boolean success, String path) {
                                dismissDialog();
                                ToastUtils.showShort(success ? "转换成功" : "转换失败");
                                TbsReaderActivity.start(PdfDemoActivity.this, path);
                            }
                        });
                    }
                });
    }

    private void pdf2Img() {
        ArrayList<String> typeList = new ArrayList<>();
        typeList.add("application/pdf");
        DefDocSelActivity.selFile(this, typeList, REQ_PDF_2_IMG);
    }

    private void pdf2Img(Uri uri) {
        PdfUtil.pdf2Img(uri, new IPdf2ImgListener() {
            @Override
            public void onStart() {
                showDialog("转换中...");
            }

            @Override
            public void onEnd(int imageCount, List<String> outputFilePaths) {
                dismissDialog();
                if (outputFilePaths == null || outputFilePaths.size() == 0) return;

                Glide.with(mDataBinding.ivRet).load(outputFilePaths.get(0)).into(mDataBinding.ivRet);
            }
        });
    }
}
